#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include "Log.hpp"

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        LOG(INFO, "./udpclient serverip serverport\n");
        exit(1);
    }

    uint16_t serverport = std::stoi(argv[2]);
    std::string serverip = argv[1];

    // 创建client的套接字标识符
    // client 不需要bind ip和port  OS在首次send的时候自动绑定
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        LOG(FATAL, "socket creat error\n");
        exit(1);
    }

    struct sockaddr_in server;
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    server.sin_port = htons(serverport);
    server.sin_family = AF_INET;

    while (1)
    {
        std::string line;
        std::cout << "Please Enter# ";
        std::getline(std::cin, line);

        // 发送
        int n = sendto(sockfd, line.c_str(), line.size(), 0, (struct sockaddr *)&server, sizeof(server));
        if (n < 0)
        {
            LOG(FATAL, "client sendto error\n");
            exit(1);
        }

        // 接受
        struct sockaddr_in temp;
        memset(&temp, 0, sizeof(temp));
        socklen_t len = sizeof(temp);
        char buff[1024];
        n = recvfrom(sockfd,buff, sizeof(buff)-1, 0, (struct sockaddr *)&temp, &len);
        if (n < 0)
        {
            LOG(FATAL, "client recvfrom error\n");
            exit(1);
        }
        // 处理
        buff[n] = 0;
        std::cout << buff<<std::endl;
    }

    ::close(sockfd);
    return 0;
}